<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-8-10
 * Time: 上午9:53
 */

namespace common\members\wodrow\tools;


class Model
{
    /**
     * 实例化模型并把所有属性赋值为空
     * @param string $model_class 类名
     * @return \yii\base\Model
     */
    public static function setAllFieldNullValueForModelByClassname($model_class)
    {
        /**
         * @var \yii\base\Model $m
         */
        $m = new $model_class;
        $attributes = $m->attributes();
        foreach ($attributes as $k => $v){
            $m->$v = null;
        }
        return $m;
    }

    /**
     * 获取 Model 错误信息中的 第一条，无错误时 返回 null
     * @param \yii\base\Model $model
     * @return mixed|string
     */
    public static function getModelError($model) {
        $errors = $model->getErrors();    //得到所有的错误信息
        if(!is_array($errors)) return '';
        $firstError = array_shift($errors);
        if(!is_array($firstError)) return '';
        return array_shift($firstError);
    }

    /**
     * @param \yii\base\Model $m1
     * @param \yii\base\Model $m2
     * @param array $excepts
     */
    public static function switchPlaceModelValue($m1, $m2, $excepts = [])
    {
        $tmp = clone $m1;
        foreach ($m1->attributes as $k => $v){
            if (!in_array($k, $excepts)){
                $m1->$k = $m2->$k;
                $m2->$k = $tmp->$k;
            }
        }
        $m1->save();
        $m2->save();
    }
}